import { defineStore } from 'pinia'
import store from 'store2'
import _ from 'lodash'
import { Message } from '@arco-design/web-vue'

export const useAppInfoListStore = defineStore('appInfoListStore', {
    state() {
        return {
            appInfoList: []
        }
    },

    actions: {
        add(app) {
            const newAppInfo = { ...app }
            const result = _.find(this.appInfoList, { 
                packageName: newAppInfo.packageName
            })
            if(result) {
                Message.info({
                    title: 'add failed',
                    content: `This "${newAppInfo.alias}" already exists!`,
                    type: 'warning',
                    duration: 2500,
                })
            } else {
                this.appInfoList.unshift(newAppInfo)
                store('appInfo', this.appInfoList)
                Message.info({
                    title: 'add appinfo',
                    content: `Add "${ newAppInfo.alias}" sucessfully!`,
                    type: 'success',
                    duration: 2500,
                })
            }
        },
        init() {
            const storedAppInfoList = store.get('appInfo');
            this.appInfoList = Array.isArray(storedAppInfoList) ? storedAppInfoList : [];
        },
        delete(app) {
            const delAppInfo = { ...app }
            _.remove(this.appInfoList, (item) => {
                return item.packageName === delAppInfo.packageName
            })
            store('appInfo', this.appInfoList)
            Message.info({
                title: 'delete appinfo',
                content: 'delete '+ delAppInfo.alias +' sucessfully!',
                type: 'success',
                duration: 2500,
            })
        },
        update(app) {
            const updateAppInfo = { ...app }
            const result = _.find(this.appInfoList, { 
                packageName: updateAppInfo.packageName
            })
            if (result) {
                _.assign(result, updateAppInfo)
                store('appInfo', this.appInfoList)
            }
            Message.info({
                title: 'update appinfo',
                content: 'update '+ updateAppInfo.alias +' sucessfully!',
                type: 'success',
                duration: 2500,
            })
        }
    }
})